package com.chen.annotation.support;

import cn.hutool.core.util.ObjUtil;
import com.chen.annotation.WxLoginUser;
import com.chen.bean.entity.UserEntity;
import com.chen.bean.enums.ResultCode;
import com.chen.bean.vo.WxUserInfo;
import com.chen.exception.BusinessException;
import com.chen.interceptor.WxLoginInterceptor;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
public class WxLoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Integer.class) && parameter.hasParameterAnnotation(WxLoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        UserEntity currentUser = WxLoginInterceptor.getCurrentUser();
        if (ObjUtil.isNull(currentUser)){
            throw new BusinessException(ResultCode.UNAUTHORIZED);
        }
        return currentUser.getId();
    }
}
